﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml;
using System.Linq;
using System.Xml.Linq;

namespace RFW.Silverlight.Weather
{
	public abstract class CurrentConditions
	{
		private string _id = string.Empty;
		private string _uri = string.Empty;

		public event System.EventHandler DownloadComplete;
		public event System.EventHandler DownloadFailed;

		public Location Location { get; set; }
		public Wind Wind { get; set; }
		public Temperature Temperature { get; set; }
		public Rain Rain { get; set; }
		public Pressure Pressure { get; set; }

		public CurrentConditions(string ID, string uri)
		{
			_id = ID;
			_uri = uri;

			this.Location = new Location();
			this.Wind = new Wind();
			this.Temperature = new Temperature();
			this.Rain = new Rain();
			this.Pressure = new Pressure();
		}

		public string ID
		{
			get { return _id; }
			set { _id = value; }
		}

		public void Get()
		{
			try
			{
				System.Net.WebClient wc = new WebClient();
				wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
				wc.DownloadStringAsync(new Uri(string.Format(_uri, _id)));
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				if (DownloadFailed != null)
					DownloadFailed(this, EventArgs.Empty);
			}
		}

		void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
		{
			try
			{
				XDocument doc = XDocument.Parse(e.Result);

				this.Location.Process(doc);
				this.Wind.Process(doc);
				this.Temperature.Process(doc);
				this.Rain.Process(doc);
				this.Pressure.Process(doc);

				if (DownloadComplete != null)
					DownloadComplete(this, EventArgs.Empty);
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
				if (DownloadFailed != null)
					DownloadFailed(this, EventArgs.Empty);
			}
		}

		public void Get(string ID)
		{
			_id = ID;
			Get();
		}
	}
}
